<?php

namespace app\store\model;

use app\common\model\Goods as GoodsModel;
use app\common\model\GoodsSkuCopy;
use app\store\service\Goods as GoodsService;
use think\Db;

/**
 * 商品模型
 * Class Goods
 * @package app\store\model
 */
class Goods extends GoodsModel
{
    /**
     * 添加商品
     * @param array $data
     * @return bool
     * @throws \think\exception\PDOException
     */
    public function add(array $data)
    {
        if (!isset($data['images']) || empty($data['images'])) {
            $this->error = '请上传商品图片';
            return false;
        }

        $data['content'] = isset($data['content']) ? $data['content'] : '';
        $data['wxapp_id'] = $data['sku']['wxapp_id'] = self::$wxapp_id;
        if ($data['goods_type'] == 1 && empty($data['goods_count'])) {
            $this->error = '请输入服务次数';
            return false;
        }


        if ($data['goods_type'] == 1 && empty($data['goods_expire'])) {
            $this->error = '请输入服务有效期';
            return false;
        }
        if ($data['goods_type'] == 2 && empty($data['goods_count_month'])) {
            $this->error = '请输入每月服务次数';
            return false;
        }
        if ($data['goods_type'] == 2 && empty($data['goods_month'])) {
            $this->error = '请输入服务月数';
            return false;
        }
        if ($data['goods_type'] == 4) {
            if(empty($data['goods_start_time']) || empty($data['goods_over_time'])) {
                $this->error = '请完善开始时间或结束时间';
                return false;
            }
            $data['goods_over_time'] = strtotime($data['goods_over_time']);
            $data['goods_start_time'] = strtotime($data['goods_start_time']);
            $data['goods_notice_time'] = strtotime($data['goods_notice_time']);
            if ($data['goods_over_time'] <= $data['goods_start_time']){
                $this->error = '时间填写有误';
                return false;
            }
        }

        if ($data['goods_type'] == 3) {
            if (empty($data['goods_meal_name']) || empty($data['goods_meal_price']) || empty($data['goods_meal_type'])) {
                $this->error = '请完善套餐信息';
                return false;
            }
            $num = count($data['goods_meal_name']);
            $sku_arr = [];
            for ($i = 0; $i <= $num - 1; $i++) {
                if (empty($data['goods_meal_name'][$i])) {
                    $this->error = '套餐名缺失';
                    return false;
                } else {
                    $sku_arr[$i]['goods_sku_name'] = $data['goods_meal_name'][$i];
                }
                if (empty($data['goods_meal_price'][$i])) {
                    $this->error = '套餐价格缺失';
                    return false;
                } else {
                    $sku_arr[$i]['goods_price'] = $data['goods_meal_price'][$i];
                }
                if (empty($data['goods_meal_type'][$i])) {
                    $this->error = '套餐预约类型缺失';
                    return false;
                } else {
                    $sku_arr[$i]['type_id'] = $data['goods_meal_type'][$i];
                }
                if(empty($data['goods_meal_num'])){
                    $data['goods_meal_num'] =3;
                    $sku_arr[$i]['goods_meal_num'] = $data['goods_meal_num'];
                }

                $sku_arr[$i]['goods_meal_num'] = $data['goods_meal_num'];

            }
            $data['sku_arr'] = $sku_arr;
        }

        // 开启事务
        $this->startTrans();
        try {
            // 添加商品
            $this->allowField(true)->save($data);
            // 商品规格
            $this->addGoodsSpec($data);
            // 商品图片
            $this->addGoodsImages($data['images']);
            $this->commit();
            return true;
        } catch (\Exception $e) {
            $this->error = $e->getMessage();
            $this->rollback();
            return false;
        }
    }

    /**
     * 添加商品图片
     * @param $images
     * @return int
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    private function addGoodsImages($images)
    {
        $this->image()->delete();
        $data = array_map(function ($image_id) {
            return [
                'image_id' => $image_id,
                'wxapp_id' => self::$wxapp_id
            ];
        }, $images);
        return $this->image()->saveAll($data);
    }

    /**
     * 编辑商品
     * @param $data
     * @return bool|mixed
     */
    public function edit($data)
    {
        log_print($data);
        if (!isset($data['images']) || empty($data['images'])) {
            $this->error = '请上传商品图片';
            return false;
        }
        $data['spec_type'] = isset($data['spec_type']) ? $data['spec_type'] : $this['spec_type'];
        $data['content'] = isset($data['content']) ? $data['content'] : '';
        $data['wxapp_id'] = $data['sku']['wxapp_id'] = self::$wxapp_id;

        if ($data['goods_type'] == 1 && empty($data['goods_count'])) {
            $this->error = '请输入服务次数';
            return false;
        }
        if ($data['goods_type'] == 1 && empty($data['goods_expire'])) {
            $this->error = '请输入服务有效期';
            return false;
        }
        if ($data['goods_type'] == 2 && empty($data['goods_count_month'])) {
            $this->error = '请输入每月服务次数';
            return false;
        }
        if ($data['goods_type'] == 2 && empty($data['goods_month'])) {
            $this->error = '请输入服务月数';
            return false;
        }
        if ($data['goods_type'] == 4) {
            if(empty($data['goods_start_time']) || empty($data['goods_over_time'])) {
                $this->error = '请完善开始时间或结束时间';
                return false;
            }
            $data['goods_over_time'] = strtotime($data['goods_over_time']);
            $data['goods_start_time'] = strtotime($data['goods_start_time']);
            $data['goods_notice_time'] = strtotime($data['goods_notice_time']);
            if ($data['goods_over_time'] <= $data['goods_start_time']){
                $this->error = '时间填写有误';
                return false;
            }
        }else{
            $data['goods_over_time'] = time();
            $data['goods_start_time'] =  time();
            $data['goods_notice_time'] =  0;
        }

        if ($data['goods_type'] == 3) {
            if (empty($data['goods_meal_name']) || empty($data['goods_meal_price']) || empty($data['goods_meal_type'])) {
                $this->error = '请完善套餐信息';
                return false;
            }
            $num = count($data['goods_meal_name']);
            $sku_arr = [];
            for ($i = 0; $i <= $num - 1; $i++) {
                if (empty($data['goods_meal_name'][$i])) {
                    $this->error = '套餐名缺失';
                    return false;
                } else {
                    $sku_arr[$i]['goods_sku_name'] = $data['goods_meal_name'][$i];
                }
                if (empty($data['goods_meal_price'][$i])) {
                    $this->error = '套餐价格缺失';
                    return false;
                } else {
                    $sku_arr[$i]['goods_price'] = $data['goods_meal_price'][$i];
                }
                if (empty($data['goods_meal_type'][$i])) {
                    $this->error = '套餐预约类型缺失';
                    return false;
                } else {
                    $sku_arr[$i]['type_id'] = $data['goods_meal_type'][$i];
                }
                if(empty($data['goods_meal_num'])){
                    $data['goods_meal_num'] =3;
                    $sku_arr[$i]['goods_meal_num'] = $data['goods_meal_num'];
                }

                $sku_arr[$i]['goods_meal_num'] = $data['goods_meal_num'];
            }
            $data['sku_arr'] = $sku_arr;
        }

        return $this->transaction(function () use ($data) {
            // 保存商品
            $this->allowField(true)->save($data);
            // 商品规格
            $this->addGoodsSpec($data, true);
            // 商品图片
            $this->addGoodsImages($data['images']);
            return true;
        });
    }

    /**
     * 添加商品规格
     * @param $data
     * @param $isUpdate
     * @throws \Exception
     */
    private function addGoodsSpec($data, $isUpdate = false)
    {
        // 更新模式: 先删除所有规格
        $model = new GoodsSku;
//        var_dump($data);die;
        $isUpdate && $model->removeAll($this['goods_id']);

        // 添加规格数据
        if ($data['spec_type'] == '10') {
            // 单规格
            $this->sku()->save($data['sku']);
        } else if ($data['spec_type'] == '20') {
            // 添加商品与规格关系记录
            $model->addGoodsSpecRel($this['goods_id'], $data['spec_many']['spec_attr']);
            // 添加商品sku
            $model->addSkuList($this['goods_id'], $data['spec_many']['spec_list']);
        }

        if (isset($data['sku_arr']) && !empty($data['sku_arr'])) {
            foreach ($data['sku_arr'] as $key => &$val) {
                $val['goods_id'] = $this['goods_id'];
                $val['spec_sku_id'] = $this['goods_id'] . $key;
                $val['wxapp_id'] = self::$wxapp_id;
                $val['form'] = 1;
            }
            $model->allowField(true)->saveAll($data['sku_arr']);

            $list = $model->where('goods_id','=', $this['goods_id'])->select();

            foreach ($list as $val)
            {
                $copy['goods_sku_id'] = $val['goods_sku_id'];
                $copy['goods_id'] = $val['goods_id'];
                $copy['image_id'] = $val['image_id'];
                $copy['goods_no'] = $val['goods_no'];
                $copy['goods_price'] = $val['goods_price'];
                $copy['line_price'] = $val['line_price'];
                $copy['type_id'] = $val['type_id'];
                $copy['goods_sku_name'] = $val['goods_sku_name'];
                $copy['wxapp_id'] = $val['wxapp_id'];
//                $copy['create_time'] = $val['create_time'];
                $check =  Db::name('goods_sku_copy')->where(['goods_sku_id'=>$val['goods_sku_id']])->find();
                if(!$check){
                    Db::name('goods_sku_copy')->insert($copy);
                }
            }
        }

    }

    /**
     * 修改商品状态
     * @param $state
     * @return false|int
     */
    public function setStatus($state)
    {
        return $this->allowField(true)->save(['goods_status' => $state ? 10 : 20]) !== false;
    }

    /**
     * 软删除
     * @return false|int
     */
    public function setDelete()
    {
        if (!GoodsService::checkIsAllowDelete($this['goods_id'])) {
            $this->error = '当前商品正在参与其他活动，不允许删除';
            return false;
        }
        return $this->allowField(true)->save(['is_delete' => 1]);
    }

    /**
     * 获取当前商品总数
     * @param array $where
     * @return int|string
     * @throws \think\Exception
     */
    public function getGoodsTotal($where = [])
    {
        return $this->where('is_delete', '=', 0)->where($where)->count();
    }

    public static function GoodsType()
    {
        return [0 => '服务商品', 1 => '次卡', 2 => '包月卡', 3 => '套餐'];
    }

}
